package com.xcity.game.achievement;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.xcity.db.entity.Player;
import com.xcity.game.event.GameEvents;

import naga.x.App;
import naga.x.game.template.TemplateService;

public class Achievement {

	@JSONField(name = "1")
	private int id;
	@JSONField(name = "2")
	private JSONObject value;
	@JSONField(name = "3")
	private State state = State.INITED;
	@JSONField(serialize = false)
	protected AchievementManager vm;
	
	public static enum State { INITED, FINISHED, REWARDED }
	
	public static final String DEFAULT_VAL_KEY = "val";
	
	@JSONField(serialize = false)
	private AchievementTemplate template;
	
	public Achievement() {}
	
	public Achievement(AchievementManager vm, AchievementTemplate template) {
		this.vm = vm;
		this.template = template;
		this.id = template.getId();
		this.value = new JSONObject();
		this.state = State.INITED;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
		this.template = App.getApp().getServiceManager().get(TemplateService.class).get(AchievementTemplate.class, id);
	}

	public JSONObject getValue() {
		return value;
	}

	public void setValue(JSONObject value) {
		this.value = value;
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}
	
	public AchievementManager getVm() {
		return vm;
	}

	public AchievementTemplate getTemplate() {
		return template;
	}
	
	public boolean update(Player owner, int... vals) {
		AchievementGroup group = template.getGroup();
		boolean succ = group.update(this, vals);
		if (succ) {
			App.getApp().getEventManager().addEvent(GameEvents.EVENT_ACHIEVE_FINISHED, owner, this);
		}
		return succ;
	}
	
	void refresh(Player owner) {
		AchievementTemplate next = App.getApp().getServiceManager().get(AchievementService.class).getNext(template);
		if (next != null) {
			this.id = next.getId();
//			this.value = new JSONObject(); // 已完成值不重置
			this.state = State.INITED;
			this.template = next;
			AchievementGroup group = template.getGroup();
			if (group.isFinished(this)) { // 有可能当前已经完成下一档的成就,所以强制检测一遍
				App.getApp().getEventManager().addEvent(GameEvents.EVENT_ACHIEVE_FINISHED, owner, this);
			}
		}
	}
	
}
